#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>


#define NUM 4
typedef void(*fun_t)();
fun_t tasks[NUM];

void print_log()
{
    printf("this is print_log\n");
}

void print_error()
{
    printf("this is print_error\n");
}

void print_signal()
{
    printf("this is print_signal\n");
}

void Init_Tasks()
{
    tasks[0] = print_log;
    tasks[1] = print_error;
    tasks[2] = print_signal;
    tasks[3] = NULL;
}


void Print()
{
    Init_Tasks();
    
    int i = 0;
    for (; tasks[i]; i++)
    {
        tasks[i]();
    }
}


int main()
{
    pid_t id = fork();

    if (id == 0)
    {
        int cnt = 10;

        while (cnt)
        {
            printf("this is a child, pid: %d, ppid: %d, cnt: %d\n", getpid(), getppid(), cnt);
            cnt--;
            sleep(1);
        }
        exit(2);
    }

    // father
    // sleep(2);
    int status = 0;
    
    // pid_t rid = waitpid(id, &status, WNOHANG); // 非阻塞等待，option: WNOHANG
    // pid_t rid = waitpid(id, &status, 0);
    while (1)
    {
        
        pid_t rid = waitpid(id, &status, WNOHANG); // 非阻塞等待，option: WNOHANG
        if (rid > 0) 
        {
            printf("wait success: status: %d, exit code: %d, exit signal: %d\n", status, (status>>8)&0xFF, status&0x7f);
            break;
        }
        else if (rid == 0)
        {
            printf("father is waiting, child is running...\n");
            printf("######################## father begin #######################\n");
            
            Print();

            printf("######################## father end   #######################\n");
        }
        else if (rid < 0)
        {
            printf("exit error: status: %d, exit code: %d, exit signal: %d\n", status, (status>>8)&0xFF, status&0x7F);
        }
        sleep(1);
    }
    
    
    //if (rid > 0)
    //    printf("wait success: status: %d, exit code: %d, exit signal: %d\n", status, (status>>8)&0xFF, (status&0x7F));
    return 0;
}
